package com.zqx.spmab.utils;

import jodd.io.FileNameUtil;
import jodd.io.NetUtil;
import jodd.io.findfile.FindFile;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.AndFileFilter;
import org.apache.commons.io.filefilter.DirectoryFileFilter;
import org.apache.commons.io.filefilter.NotFileFilter;
import org.apache.commons.io.filefilter.SuffixFileFilter;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;
import org.springframework.web.multipart.commons.CommonsMultipartResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.Iterator;

/**
 * Created by Zqx on 2018/4/24.
 */
public class FileUtil {
    public static final int BUFFERSIZE = 2048;

    private FileUtil() {
        throw new Error("工具类不能实例化");
    }

    public static void createParentDirs(String path) throws IOException {
        (new File(getFilePath(path))).mkdirs();
    }

    public static void downloadFileFromUrl(String url, File targetFile) throws IOException {
        NetUtil.downloadFile(url, targetFile);
    }

    public static void uploadFile(File upload, String targetPathNameWithoutSuffix) {
        try {
            File e = new File(targetPathNameWithoutSuffix + "." + getSuffix(upload.getName()));
            createParentDirs(targetPathNameWithoutSuffix + "." + getSuffix(upload.getName()));
            FileUtils.copyFile(upload, e);
        } catch (IOException var3) {
            var3.printStackTrace();
        }

    }

    public static void uploadFileSpringMVC(MultipartFile cmFile, String targetPathNameWithoutSuffix) throws Exception {
        if(!cmFile.isEmpty()) {
            File file = new File(targetPathNameWithoutSuffix + "." + getSuffix(cmFile.getOriginalFilename()));
            createParentDirs(targetPathNameWithoutSuffix + "." + getSuffix(cmFile.getName()));
            /*cmFile.getFileItem().write(file);*/
        }

    }

    public static void uploadFilesSpringMVC(HttpServletRequest request, String targetPath) throws IllegalStateException, IOException {
        CommonsMultipartResolver multipartResolver = new CommonsMultipartResolver(request.getSession().getServletContext());
        if(multipartResolver.isMultipart(request)) {
            MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
            Iterator iter = multiRequest.getFileNames();

            while(iter.hasNext()) {
                MultipartFile file = multiRequest.getFile((String)iter.next());
                if(file != null) {
                    String myFileName = file.getOriginalFilename();
                    if(!StringUtil.isNullOrBlank(myFileName)) {
                        String path = targetPath + file.getOriginalFilename();
                        File localFile = new File(path);
                        file.transferTo(localFile);
                    }
                }
            }
        }

    }

    public static void delete(File destFile) throws IOException {
        jodd.io.FileUtil.delete(destFile);
    }

    public static void cleanDir(File destDir) throws IOException {
        jodd.io.FileUtil.cleanDir(destDir);
    }

    public static boolean renameFile(String resFilePath, String newFileName) {
        String newFilePath = formatPath(getFilePath(resFilePath) + newFileName);
        File resFile = new File(resFilePath);
        File newFile = new File(newFilePath);
        return resFile.renameTo(newFile);
    }

    public static long genFileSize(String distFilePath) {
        File distFile = new File(distFilePath);
        return distFile.isFile()?distFile.length():(distFile.isDirectory()?FileUtils.sizeOfDirectory(distFile):-1L);
    }

    public static String[] listFilebySuffix(String folder, String suffix) {
        SuffixFileFilter fileFilter1 = new SuffixFileFilter(suffix);
        NotFileFilter fileFilter2 = new NotFileFilter(DirectoryFileFilter.INSTANCE);
        AndFileFilter filenameFilter = new AndFileFilter(fileFilter1, fileFilter2);
        return (new File(folder)).list(filenameFilter);
    }

    public static Iterator<File> findFile(String folder, boolean recursive, boolean includeDirs) {
        return (new FindFile()).setRecursive(recursive).setIncludeDirs(includeDirs).searchPath(folder).iterator();
    }

    public static void writeFileToBrowser(InputStream inputStream, HttpServletResponse response) {
        byte[] buff = new byte[2048];
        boolean len = true;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {
            bis = new BufferedInputStream(inputStream);
            bos = new BufferedOutputStream(response.getOutputStream());

            int len1;
            while((len1 = bis.read(buff, 0, buff.length)) != -1) {
                bos.write(buff, 0, len1);
            }
        } catch (IOException var15) {
            var15.printStackTrace();
        } finally {
            try {
                if(bis != null) {
                    bis.close();
                }

                if(bos != null) {
                    bos.close();
                }
            } catch (Exception var14) {
                var14.printStackTrace();
            }

        }

    }

    public static void download(String path, String targetNameWithoutSuffix, HttpServletResponse response) throws FileNotFoundException {
        response.reset();
        response.setContentType("application/x-msdownload");
        response.setContentLength((int)(new File(path)).length());

        try {
            String buff = URLEncoder.encode(targetNameWithoutSuffix + "." + getSuffix(path), "UTF-8");
            response.addHeader("Content-Disposition", "attachment;filename=" + buff);
        } catch (UnsupportedEncodingException var17) {
            var17.printStackTrace();
        }

        byte[] buff1 = new byte[2048];
        boolean len = true;
        BufferedInputStream bis = null;
        BufferedOutputStream bos = null;

        try {
            bis = new BufferedInputStream(new FileInputStream(new File(path)));
            bos = new BufferedOutputStream(response.getOutputStream());
            response.setContentType("application/octet-stream");

            int len1;
            while((len1 = bis.read(buff1, 0, buff1.length)) != -1) {
                bos.write(buff1, 0, len1);
            }
        } catch (IOException var18) {
            var18.printStackTrace();
        } finally {
            try {
                if(bis != null) {
                    bis.close();
                }

                if(bos != null) {
                    bos.close();
                }
            } catch (Exception var16) {
                var16.printStackTrace();
            }

        }

    }

    public static String getFileType(String suffix) {
        return suffix != null?(!suffix.equals("jpg") && !suffix.equals("png") && !suffix.equals("gif") && !suffix.equals("bmp")?(!suffix.equals("mp4") && !suffix.equals("wmv") && !suffix.equals("avi") && !suffix.equals("flv") && !suffix.equals("rm") && !suffix.equals("rmvb") && !suffix.equals("mkv")?(!suffix.equals("mp3") && !suffix.equals("wav") && !suffix.equals("midi")?(!suffix.equals("doc") && !suffix.equals("docx") && !suffix.equals("xls") && !suffix.equals("xlsx") && !suffix.equals("ppt") && !suffix.equals("ppts") && !suffix.equals("txt") && !suffix.equals("wps") && !suffix.equals("et") && !suffix.equals("dps")?(!suffix.equals("rar") && !suffix.equals("zip") && !suffix.equals("tar") && !suffix.equals("tgz") && !suffix.equals("gz")?"other":"rar"):"doc"):"audio"):"video"):"img"):"other";
    }

    public static String getSuffix(String fileName) {
        return FileNameUtil.getExtension(fileName);
    }

    public static String getFileNameWithoutSuffixByPath(String path) {
        return FileNameUtil.getBaseName(path);
    }

    public static String getFileNameWithSuffixByPath(String path) {
        return FileNameUtil.getName(path);
    }

    public static String getFilePath(String path) {
        return FileNameUtil.getFullPath(path);
    }

    public static String getFilePathNoEndSeparator(String path) {
        return FileNameUtil.getFullPathNoEndSeparator(path);
    }

    public static String getFileRelativePath(String path, String basePath) {
        return path.replaceFirst(basePath, "");
    }

    public static String formatPath(String path) {
        return FileNameUtil.normalize(path);
    }
}
